package com.byxy.computer.student.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.byxy.computer.student.entity.Student;
import com.byxy.computer.student.service.LessonMaterialService;
import com.byxy.computer.student.service.StudentService;

/**
 * @author Daniel
 * @E-Mail iva0512@gmail.com
 * @Date 2016年9月25日
 */
@Controller
@RequestMapping("std")
@SessionAttributes("student")
public class StudentController {

	@Autowired
	private StudentService studentService;
	@Autowired
	private LessonMaterialService lessonMaterialService;

	// 学生主页
	@RequestMapping(value = { "" }, method = RequestMethod.GET)
	public String index() {
		return "redirect:std/";
	}

	// 学生主页
	@RequestMapping(value = { "index", "/" }, method = RequestMethod.GET)
	public String index2() {
		return "student/login";
	}

	// 学生登录
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(Student student, String pwd, Model model) {
		if (student.getUid() == null || student.getUid().equals("") || pwd == null || pwd.equals("")) {
			return "redirect:index";
		}
		Student s = studentService.get(student);
		if (s != null && s.getUid() != null && !"".equals(s.getUid())) {

			model.addAttribute("student", s);
			if ("√".equals(s.getStats()))
				return "redirect:student";
			else
				return "redirect:sign";
		} else {
			return "redirect:index";
		}
	}

	// 学生退出
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(Model model) {
		model.asMap().remove("student");
		return "redirect:std/index";
	}

	// 学生点名页面
	@RequestMapping(value = "sign", method = RequestMethod.GET)
	public String sign() {
		return "student/sign";
	}

	// 学生点名
	@RequestMapping(value = "sign", method = RequestMethod.POST)
	public String sign(Student student, Model model, HttpServletRequest req) {
		student.setComputername(req.getRemoteHost());
		Student s = studentService.sign(student);
		if (s != null) {
			model.addAttribute("student", s);
			return "redirect:student";
		}
		return "student/sign";
	}

	// 学生交作业页面
	@RequestMapping(value = "student", method = RequestMethod.GET)
	public String list(Model model) {
		model.addAttribute("download", lessonMaterialService.listAll());
		if (model.containsAttribute("student")) {
			Student s = (Student) model.asMap().get("student");
			model.addAttribute("student", studentService.get(s));
		}
		return "student/student";
	}

	// 学生交作业
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(Student student, MultipartFile attach, HttpServletRequest req) {
		String strDate = DateFormat.getDateInstance().format(new Date());
		String path = "/upload/" + strDate;
		String realpath = req.getSession().getServletContext().getRealPath(path);
		String filename = attach.getOriginalFilename();
		int len = filename.lastIndexOf(".");
		Student s = studentService.get(student);
		if (len > 0) {
			File f = new File(realpath + "/" + s.getUid() + "_" + s.getUsername() + filename.substring(len));
			try {
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
				studentService.upload(s, strDate + "/" + s.getUid() + "_" + s.getUsername() + filename.substring(len),
						(int) attach.getSize());
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {

		}
		return "redirect:/std/student";
	}

	// 下载学生的作业
	@RequestMapping("download")
	public void download(String fileName, HttpServletRequest request, HttpServletResponse response) {
		String realpath = request.getSession().getServletContext().getRealPath("/");
		int len = fileName.lastIndexOf("/");
		if (len > 0) {
			String name = fileName.substring(len + 1);
			File file = new File(realpath + "/upload/" + fileName);
			if (file.exists()) {
				try {
					String realname = new String(name.getBytes("gbk"), "ISO-8859-1");
					response.reset();
					response.setCharacterEncoding("utf-8");
					response.setContentType("multipart/form-data");
					// response.setContentType("application/x-msdownload");
					response.setHeader("Content-Disposition", "attachment;fileName=" + realname);
					InputStream inputStream = new FileInputStream(file);
					int fileLength = (int) file.length();
					response.setContentLength(fileLength);
					OutputStream os = response.getOutputStream();
					byte[] b = new byte[2048];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}
					inputStream.close();
					os.close();
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// @ResponseBody
	// @RequestMapping(value = "list", method = RequestMethod.POST)
	// public AjaxEasyUIPage list() {
	// AjaxEasyUIPage json = new AjaxEasyUIPage();
	// List<Student> records = smsRecordsService.listAll();
	// json.setRows(records);
	// json.setTotal((long) records.size());
	// return json;
	// }
	//
	// @ResponseBody
	// @RequestMapping(value = "list", method = RequestMethod.POST, params = {
	// "page", "rows" })
	// public AjaxEasyUIPage list(int page, int rows) {
	// return smsRecordsService.listPage(page, rows);
	// }
	//
	// @RequestMapping(value = "exportExcl", method = RequestMethod.GET)
	// public void exportExcl(HttpServletRequest request,
	// HttpServletResponse response) throws IOException {
	// String excelTitle = Student.class.getSimpleName();
	// List<Student> records = smsRecordsService.listAll();
	// String fileName = excelTitle + ".xlsx";
	// new ExportExcel(excelTitle, Student.class).setDataList(records)
	// .write(response, fileName).dispose();
	// }
}
